// ======================== 数据库操作方法 ====================== //
import { invokeAsyncAPi } from '@/xz-fn.js'
import { parseTime } from '@/utils'

const valueFormat = function (val) {
  if (val === null) {
    return 'null'
  }
  if (Number.isInteger(val)) {
    return val
  }
  if (val === undefined || val === "'") {
    val = ''
  } else if (Array.isArray(val)) {
    val = val.length ? JSON.stringify(val) : ''
  } else {
    val = val.replace(/'/g, '')
  }
  return `'${val}'`
}

export default class Db {
  constructor (tableName, tableFields) {
    this.tableName = tableName
    this.tableFields = tableFields
    this.fields = tableFields.map(({ key }) => key)
  }
  getDefaultData () {
    const data = {}
    this.tableFields.forEach(item => {
      const def = item.default
      if (typeof def !== 'undefined') {
        data[item.key] = typeof def === 'function' ? def() : def
      }
    })
    return data
  }
  /**
 * 查询
 * @param {String} where
 * @return {Promise}
 */
  async get (where) {
    const sqlStr = `SELECT * FROM ${this.tableName} WHERE ${where}`
    // console.log(sqlStr)
    const result = await invokeAsyncAPi('remind_query', sqlStr)
    return result || []
  }
  /**
 * 查询数量
 * @param {Object} sqlStr
 * @return {Promise}
 */
  async getCount (where, distinct) {
    const sqlStr = `SELECT COUNT(${distinct ? 'DISTINCT ' + distinct : '*'}) AS COUNT FROM ${this.tableName} WHERE ${where}`
    // console.log(sqlStr)
    const result = await invokeAsyncAPi('remind_query', sqlStr)
    return (result && result[0] && result[0]['COUNT']) || 0
  }
  /**
  * 更新数据
  * @param {Object} data
  * @param {String} where
  * @return {Promise}
  */
  put (data, where, setDef = false) {
    const obj = Object.assign({
      syncStatus: 0,
      modifyPointingDate: parseTime(new Date(), '{y}-{m}-{d}T{h}:{i}:{s}.{S}')
    }, data)
    const sqlStr = this.getPutSql(obj, where, setDef)
    return invokeAsyncAPi('remind_update_sync', sqlStr)
  }
  getPutSql (data, where, setDef = false) {
    let def = {}
    if (setDef) {
      def = this.getDefaultData()
    }
    const obj = Object.assign(def, data)
    const keys = Object.keys(obj).filter(key => this.fields.includes(key))
    return `UPDATE ${this.tableName} SET ${keys.map(key => key + '=' + valueFormat(obj[key])).join(',')} WHERE ${where}`
  }
  /**
  * 新增数据
  * @param {Object} data
  * @return {Promise}
  */
  add (list) {
    if (!Array.isArray(list)) {
      list = [list]
    }
    if (!list.length) return Promise.resolve()
    let sqlStr = ''
    const values = []
    const keys = this.fields
    for (const data of list) {
      const def = this.getDefaultData()
      const subData = Object.assign(def, data)
      values.push('(' + keys.map(key => valueFormat(subData[key])).join(',') + ')')
    }
    sqlStr = `INSERT INTO ${this.tableName} (${keys.join(
      ','
    )}) VALUES ${values.join(',')}`
    // console.log(sqlStr)
    return invokeAsyncAPi('remind_add', sqlStr)
  }
  /**
 * 删除数据
 * @param {String} where
 * @return {Promise}
 */
  delete (where) {
    const sqlStr = `DELETE FROM ${this.tableName} WHERE ${where}`
    // console.log(sqlStr)
    return invokeAsyncAPi('remind_del', sqlStr)
  }
  getDeleteSql (where) {
    return `DELETE FROM ${this.tableName} WHERE ${where}`
  }
  /**
 * 事务处理
 * @param {Array} list sql集合
 * @return {Promise}
 */
  transaction (list) {
    if (!list.length) return Promise.resolve()
    return invokeAsyncAPi(' ', list)
  }
}
